package api

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"go-gin-example/pkg/app"
	"go.uber.org/zap"
	"net/http"

	"go-gin-example/models"
	"go-gin-example/pkg/e"
	"go-gin-example/pkg/util"
)

type auth struct {
	Username string `valid:"Required; MaxSize(50)"`
	Password string `valid:"Required; MaxSize(50)"`
}

// GetAuth
// @tags  用户登录接口
// @Summary 用户获取token
// @Produce json
// @Param username query string true "username"
// @Param password query string true "password"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /auth [get]
// @securitydefinitions.basic
func GetAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	username := c.Query("username")
	password := c.Query("password")

	valid := validation.Validation{}
	a := auth{Username: username, Password: password}
	ok, err := valid.Valid(&a)
	if !ok {
		zap.L().Error("form valid error", zap.Error(err))
		appG.Response(http.StatusBadRequest, e.InvalidParams, nil)
		return
	}

	data := make(map[string]interface{})

	isExist := models.CheckAuth(username, password)
	if isExist {
		token, err := util.GenerateToken(username, password)
		if err != nil {
			zap.L().Error("token gender error", zap.Error(err))
			appG.Response(http.StatusOK, e.ErrorAuthToken, nil)
			return
		} else {
			zap.L().Info("token gender success", zap.String("token", token))
			data["token"] = token
			appG.Response(http.StatusOK, e.SUCCESS, data)
			return
		}
	} else {
		// 用户名密码不存在
		zap.L().Error("username or password error", zap.String("username", username), zap.String("password", password))
		appG.Response(http.StatusOK, e.ErrorAuthToken, nil)
		return
	}
}
